//
//  TMWillCommentController.m
//  国学商家管理
//
//  Created by Tao Li on 2018/7/4.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "TMWillCommentController.h"
#import "TZImagePickerController.h"
#import "TMImageShowView.h"
#import "TMMyOrderModel.h"
#import "TMUserViewModel.h"
#import "UIImage+TMimageCloor.h"
@interface TMWillCommentController ()<TZImagePickerControllerDelegate,UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *courseImage;
@property (weak, nonatomic) IBOutlet UILabel *courseName;
@property (weak, nonatomic) IBOutlet UILabel *coursePrice;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *businessBtnCollect;
@property (weak, nonatomic) IBOutlet UITextView *businessTextView;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *teacherBtnCollect;
@property (weak, nonatomic) IBOutlet UITextView *teacherTextView;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *courseBtnCollect;
@property (weak, nonatomic) IBOutlet UITextView *courseTextView;
@property (nonatomic, strong) TMImageShowView *showView;
@property (nonatomic, strong) TMImageShowView *showView2;
@property (nonatomic, strong) TMImageShowView *showView3;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *buttomConst1;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *buttomConst2;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *buttomConst3;

@property (nonatomic, strong) NSMutableArray *imageArray;
@property (nonatomic, strong) NSMutableArray *urlArray;
@property (nonatomic, strong) NSMutableArray *imageArray2;
@property (nonatomic, strong) NSMutableArray *urlArray2;
@property (nonatomic, strong) NSMutableArray *imageArray3;
@property (nonatomic, strong) NSMutableArray *urlArray3;
@property (weak, nonatomic) IBOutlet UIView *fristImageView;
@property (weak, nonatomic) IBOutlet UIView *secondImageView;
@property (weak, nonatomic) IBOutlet UIView *thridImageView;
@property (weak, nonatomic) IBOutlet UILabel *placehilder1;
@property (weak, nonatomic) IBOutlet UILabel *placehilder2;
@property (weak, nonatomic) IBOutlet UILabel *placehilder3;
@property (nonatomic, assign) NSInteger skills;
@property (nonatomic, strong) NSMutableDictionary *param;
@property (nonatomic, strong) TMUserViewModel *viewModel;
@property (nonatomic, strong) NSMutableArray *bussinessStars;
@property (nonatomic, strong) NSMutableArray *teacherStars;
@property (nonatomic, strong) NSMutableArray *courseStars;
@end

@implementation TMWillCommentController
-(NSMutableDictionary *)param{
    if (!_param) {
        _param = [NSMutableDictionary dictionary];
    }
    return _param;
}
//- (NSMutableArray *)bussinessStars{
//    if (!_bussinessStars) {
//        _bussinessStars = [NSMutableArray array];
//    }
//    return _bussinessStars;
//}
//- (NSMutableArray *)courseStars{
//    if (!_courseStars) {
//        _courseStars = [NSMutableArray array];
//    }
//    return _courseStars;
//}
//- (NSMutableArray *)teacherStars{
//    if (!_teacherStars) {
//        _teacherStars = [NSMutableArray array];
//    }
//    return _teacherStars;
//}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"评价";
    [self displayImagesView];
    self.viewModel = [[TMUserViewModel alloc]init];
    self.courseTextView.delegate = self;
    self.teacherTextView.delegate = self;
    self.businessTextView.delegate = self;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(insert:) name:UITextViewTextDidChangeNotification object:nil];
    self.courseName.text = self.models.name;
    self.coursePrice.text = [NSString stringWithFormat:@"¥%.02f", self.models.price];
    self.courseImage.contentMode = UIViewContentModeScaleAspectFill;
    self.courseImage.clipsToBounds = YES;
    if (self.models.pic.count) {
        
        [self.courseImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithBaseUrl:self.models.pic[0]]] placeholderImage:kPlaceholder completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        }];
    }
}
- (void)insert:(UITextView *)textview{
    if (self.businessTextView.text.length>0) {
        self.placehilder1.hidden = YES;
    }else{
        self.placehilder1.hidden = NO;
    }
    if (self.teacherTextView.text.length>0) {
        self.placehilder2.hidden = YES;
    }else{
        self.placehilder2.hidden = NO;
    }
    if (self.courseTextView.text.length>0) {
        self.placehilder3.hidden = YES;
    }else{
        self.placehilder3.hidden = NO;
    }
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
//    if ([text isEqualToString:@"\n"]) {
//        [textView resignFirstResponder];
//        return NO;
//    }
//    if (textView == self.textView) {
//        //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
//        if (range.length == 1 && text.length == 0) {
//            return YES;
//        }
//        //so easy
//        else if (self.textView.text.length >= 100) {
//            self.textView.text = [textView.text substringToIndex:100];
//            return NO;
//        }
//    }
//    return YES;
//}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return false;
    }
    return true;
}
- (IBAction)commentAction:(UIButton *)sender {
    [self.param setValue:@(self.models.sid) forKey:@"sid"];
//    NSInteger count1 = 0;
//    for (UIButton *btn in self.businessBtnCollect) {
//        if (btn.selected == YES) {
//            count1 ++;
//        }
//    }
    [self.param setValue:@(self.bussinessStars.count) forKey:@"s_star"];
    [self.param setValue:self.businessTextView.text forKey:@"s_content"];
    NSString *urlstr = @"";
    for (NSString *str in self.urlArray) {
        urlstr = [NSString stringWithFormat:@"%@,%@", urlstr,str];
    }
    if (urlstr.length >0) {
        [self.param setValue:[urlstr substringFromIndex:1] forKey:@"s_pic"];
    }
    
    [self.param setValue:@(self.models.tid) forKey:@"tid"];
    NSInteger count2 = 0;
    for (UIButton *btn in self.teacherBtnCollect) {
        if (btn.selected == YES) {
            count2 ++;
        }
    }
    [self.param setValue:@(self.teacherStars.count) forKey:@"t_star"];
    [self.param setValue:self.businessTextView.text forKey:@"t_content"];
    NSString *urlstr2 = @"";
    for (NSString *str in self.urlArray2) {
        urlstr2 = [NSString stringWithFormat:@"%@,%@", urlstr2,str];
    }
    if (urlstr2.length >0) {
        [self.param setValue:[urlstr2 substringFromIndex:1] forKey:@"t_pic"];
    }
    
    [self.param setValue:@(self.models.cid) forKey:@"cid"];
    NSInteger count3 = 0;
    for (UIButton *btn in self.courseBtnCollect) {
        if (btn.selected == YES) {
            count3 ++;
        }
    }
    [self.param setValue:@(self.courseStars.count) forKey:@"c_star"];
    [self.param setValue:self.courseTextView.text forKey:@"c_content"];
    NSString *urlstr3 = @"";
    for (NSString *str in self.urlArray3) {
        urlstr3 = [NSString stringWithFormat:@"%@,%@", urlstr3,str];
    }
    if (urlstr3.length >0) {
        [self.param setValue:[urlstr3 substringFromIndex:1] forKey:@"c_pic"];
    }
    [self.param setValue:[TMUserManager deaufatManager].userModel.token forKey:@"token"];
    [self.param setValue:@([TMUserManager deaufatManager].userModel.uid) forKey:@"uid"];
    [self.param setValue:@(self.models.oid) forKey:@"order_id"];
    [self.viewModel getCommitCommendWith:self.param Success:^(id responseObject) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    } failed:^(NSString *error) {

    }];
    
}
- (IBAction)courseCheckAction:(UIButton *)sender {
    //40..44
//    return;
    sender.selected = !sender.selected;
    if (sender.selected == YES) {
        if (sender.tag -39 >0) {
            self.courseStars = [NSMutableArray array];
            for (int i = 0; i< sender.tag -39; i ++) {
                UIButton *btn = [self.view viewWithTag:i + 40];
                btn.selected = YES;
                [self.courseStars addObject:btn];
            }
            [self displayArray:self.courseStars];
        }
    }else{
        [self.courseStars enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ((UIButton *)obj == sender) {
                [self.courseStars removeObject:sender];
            }
        }];
        [self displayArray:self.courseStars];
    }
}
- (IBAction)teacherCheckAction:(UIButton *)sender {
    //30..34
//    return;
    sender.selected = !sender.selected;
    if (sender.selected == YES) {
        self.teacherStars = [NSMutableArray array];
        if (sender.tag -29 >0) {
            for (int i = 0; i< sender.tag -29; i ++) {
                UIButton *btn = [self.view viewWithTag:i + 30];
                btn.selected = YES;
                [self.teacherStars addObject:btn];
            }
            [self displayArray:self.teacherStars];
        }
    }else{
        [self.teacherStars enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ((UIButton *)obj == sender) {
                [self.teacherStars removeObject:sender];
            }
        }];
        [self displayArray:self.teacherStars];
    }
}
- (IBAction)businessCheckAction:(UIButton *)sender {
//    return;
    sender.selected = !sender.selected;
    //20..24
    if (sender.selected == YES) {
        self.bussinessStars = [NSMutableArray array];
        if (sender.tag -19 >0) {
            for (int i = 0; i< sender.tag -19; i ++) {
                UIButton *btn = [self.view viewWithTag:i + 20];
                btn.selected = YES;
                [self.bussinessStars addObject:btn];
            }
            [self displayArray:self.bussinessStars];
        }
    }else{
        [self.bussinessStars enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ((UIButton *)obj == sender) {
                [self.bussinessStars removeObject:sender];
            }
        }];
         [self displayArray:self.bussinessStars];
    }
}
- (void)displayArray:(NSMutableArray *)list{
    UIButton *btnes = list.lastObject;
    for (UIButton *tns in list) {
        if (tns.tag < btnes.tag) {
            tns.userInteractionEnabled = NO;
            tns.selected = YES;
        }
        if (tns.tag == btnes.tag) {
            tns.userInteractionEnabled = YES;
            tns.selected = YES;
        }
    }
//    [self.tableView reloadData];
    
}
#pragma mark - Table view data source
-(void)submitPictureToServer :(NSInteger)isSkills{
    self.skills = isSkills;
    if (isSkills == 1) {
        if (self.imageArray.count>= 3) {
            [TMProgressHUD showInfoWithStyleDarkStatus:@"您已选择了3张图片！"];
            return;
        }
    }
    if (isSkills == 2) {
        if (self.imageArray2.count>= 3) {
            [TMProgressHUD showInfoWithStyleDarkStatus:@"您已选择了3张图片！"];
            return;
        }
    }
    if (isSkills == 3) {
        if (self.imageArray3.count>= 3) {
            [TMProgressHUD showInfoWithStyleDarkStatus:@"您已选择了3张图片！"];
            return;
        }
    }
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"从相册获取" otherButtonTitles:nil, nil];
    [sheet showInView:self.view];
    
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSInteger counts = 0;
    if (self.skills == 1) {
        counts = self.imageArray.count;
    }
    if (self.skills == 2) {
        counts = self.imageArray2.count;
    }
    if (self.skills == 3) {
        counts = self.imageArray3.count;
    }
    if (buttonIndex == 0){
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:3-counts delegate:self];
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isok) {
            if (self.skills == 1) {
                [self.imageArray addObjectsFromArray:photos];
            }
            if (self.skills == 2) {
                [self.imageArray2 addObjectsFromArray:photos];
            }
            if (self.skills == 3) {
                [self.imageArray3 addObjectsFromArray:photos];
            }
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                for (int i=1; i<assets.count+1; i++) {
                    [TMProgressHUD showProgress:i/assets.count status:@"上传图片中..."];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [TMUserManager changeUserIcon:photos[i-1] Success:^(id urls) {
                            NSLog(@"%@", urls);
                            if (self.skills ==1) {
                                [self.urlArray addObject:(NSString *)urls];
                            }
                            if (self.skills ==2) {
                                [self.urlArray2 addObject:(NSString *)urls];
                            }
                            if (self.skills ==3) {
                                [self.urlArray3 addObject:(NSString *)urls];
                            }
                            if (i == assets.count) {
                                [TMProgressHUD dismiss];
                            }else{
                                
                            }
                        }];
                    });
                }
            });
            if (self.skills == 1) {
                self.showView.isNetworkImage = NO;
                self.showView.imageArray = self.imageArray.mutableCopy;
            }
            if (self.skills == 2) {
                self.showView2.isNetworkImage = NO;
                self.showView2.imageArray = self.imageArray2.mutableCopy;
            }
            if (self.skills == 3) {
                self.showView3.isNetworkImage = NO;
                self.showView3.imageArray = self.imageArray3.mutableCopy;
            }
            [self.tableView reloadData];
        }];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
    }
}
#pragma mark ------相册回调方法----------
- (void)displayImagesView{
    if (kWindowW == 320) {
        self.buttomConst1.constant = 100;
        self.buttomConst2.constant = 100;
        self.buttomConst3.constant = 100;
    }else{
        self.buttomConst1.constant = 125;
        self.buttomConst2.constant = 125;
        self.buttomConst3.constant = 125;
    }
    self.showView2.frame =self.secondImageView.bounds;
    [self.secondImageView addSubview:self.showView2];
    
    self.showView.frame =self.secondImageView.bounds;
    [self.fristImageView addSubview:self.showView];
    
    self.showView3.frame =self.thridImageView.bounds;
    [self.thridImageView addSubview:self.showView3];
    
    __weak typeof(self) weakself = self;
    self.showView.block = ^{
        [weakself submitPictureToServer:1];
    };
    self.showView.deleteBlock = ^(NSInteger index) {
        if (weakself.urlArray) {
            [weakself.urlArray removeObjectAtIndex:index];
            [weakself.imageArray removeObjectAtIndex:index];
            [weakself.tableView reloadData];
        }
    };
    self.showView2.block = ^{
        [weakself submitPictureToServer:2];
    };
    self.showView2.deleteBlock = ^(NSInteger index) {
        if (weakself.urlArray2) {
            [weakself.urlArray2 removeObjectAtIndex:index];
            [weakself.imageArray2 removeObjectAtIndex:index];
            [weakself.tableView reloadData];
        }
    };
    self.showView3.block = ^{
        [weakself submitPictureToServer:3];
    };
    self.showView3.deleteBlock = ^(NSInteger index) {
        if (weakself.urlArray3) {
            [weakself.urlArray3 removeObjectAtIndex:index];
            [weakself.imageArray3 removeObjectAtIndex:index];
            [weakself.tableView reloadData];
        }
    };
}
- (NSMutableArray *)imageArray {
    if (_imageArray ==nil) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}
- (NSMutableArray *)urlArray {
    if (_urlArray ==nil) {
        _urlArray = [NSMutableArray array];
    }
    return _urlArray;
}- (NSMutableArray *)imageArray2 {
    if (_imageArray2 ==nil) {
        _imageArray2 = [NSMutableArray array];
    }
    return _imageArray2;
}
- (NSMutableArray *)urlArray2 {
    if (_urlArray2 ==nil) {
        _urlArray2 = [NSMutableArray array];
    }
    return _urlArray2;
}- (NSMutableArray *)imageArray3 {
    if (_imageArray3 ==nil) {
        _imageArray3 = [NSMutableArray array];
    }
    return _imageArray3;
}
- (NSMutableArray *)urlArray3 {
    if (_urlArray3 ==nil) {
        _urlArray3 = [NSMutableArray array];
    }
    return _urlArray3;
}
-(TMImageShowView *)showView{
    if (!_showView) {
        _showView = [[NSBundle mainBundle] loadNibNamed:@"TMImageShowView" owner:nil options:nil][0];
    }
    return _showView;
}
-(TMImageShowView *)showView2{
    if (!_showView2) {
        _showView2 = [[NSBundle mainBundle] loadNibNamed:@"TMImageShowView" owner:nil options:nil][0];
    }
    return _showView2;
}
-(TMImageShowView *)showView3{
    if (!_showView3) {
        _showView3 = [[NSBundle mainBundle] loadNibNamed:@"TMImageShowView" owner:nil options:nil][0];
    }
    return _showView3;
}


@end
